package com.example.myspringtest.utils;

import org.springframework.cglib.core.DebuggingClassWriter;
import org.springframework.cglib.proxy.Enhancer;
import org.springframework.cglib.proxy.MethodInterceptor;
import org.springframework.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CGLIB代理工厂
 * 使用CGLIB为无接口的类创建动态代理，其实现原理是生成目标类(必须能够被继承，即非final修饰的类)的子类，被增强的子类即为代理对象
 *
 * @author WanAkiko
 */
public class CglibFactory<T> implements MethodInterceptor {

    private final T target;

    public CglibFactory(T target) {
        this.target = target;
    }
    public Object myCglibCreator(Class<?> tClass, Class[] interfaces) {

        System.out.println("System.getProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY) = " + System.getProperty(DebuggingClassWriter.DEBUG_LOCATION_PROPERTY));

        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(tClass); // 指定目标类，采用子类增强父类
        // MethodInterceptor底层即实现了Callback接口，因此在setCallback()中传入this即可
        enhancer.setInterfaces(interfaces);
        enhancer.setCallback(this); // 设置回调接口对象
        Object o = enhancer.create();// 创建Cglib动态代理对象
        Class<?> aClass = o.getClass();
        return o;
    }

    @Override
    public Object intercept(Object o, Method method, Object[] objects, MethodProxy methodProxy) throws Throwable {
        Object invoke = methodProxy.invoke(target, objects);
        if (null != invoke) {
            invoke = ((String) invoke).toUpperCase();
        }
        return invoke;
    }

}
